<template>
  <div id="homePage">
    <template v-if="currentUser">
      <div class="card-grid" v-if="currentUser.isTeacher === 0">
        <div v-for="item in studentBoxList" :key="item.title" class="card">
          <div class="card-header">
            <div class="icon-wrap">
              <component :is="item.icon" class="icon" />
            </div>
            <span class="title">{{ item.title }}</span>
          </div>
          <div class="card-body">
            <span class="number" v-if="item.title === '总活动数'">{{ item.num }} / {{ item.content }}</span>
            <span class="number" v-else>{{ item.content }}</span>
            <span class="unit">{{ item.unit }}</span>
          </div>
        </div>
      </div>
      <!-- 图表 -->
      <div class="chart-wrapper">
        <div id="chart-pie"></div>
        <div id="chart-right"></div>
      </div>
      <div class="chart-wrapper">
        <div id="chart-line"></div>
      </div>
    </template>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <p>请先登录后查看首页内容</p>
    </div>
  </div>
</template>

<!-- 顶部四个盒子 -->
<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, nextTick, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { AppstoreOutlined, MailOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'
import { sortRank, lineChart, pieChart } from '@/api/echarts/option'
import {
  getHotRaces,
  getTeacherInstructCount,
  getSecondClassCountYear,
  getContestTeacherInstructCount,
  getSecondTeacherInstructCount,
  getStudentSecondClassCount,
  getStudentInnovationCount,
  getStudentJoinCount,
  getParticipationRateByUser,
} from "@/api/echarts/statistics";


// 用户信息（Pinia）
const user = useUserStore()

console.log(user.userInfo)

// 兼容两种 userInfo 结构：直接对象或 { data: UserInfo }
const currentUser = computed(() => {
  const info = user.userInfo as any
  return info && info.data ? info.data : info
})

// 主题色（供样式变量使用）
const theme = '#06b6d4'
// 学生端顶部数据盒子（占位数据，避免运行时未定义报错）
const studentBoxList = ref([
  { title: '总活动数', num: 0, content: 0, unit: '个', icon: AppstoreOutlined },
  { title: '已参加', content: 0, unit: '个', icon: MailOutlined },
  { title: '已完成', content: 0, unit: '个', icon: AppstoreOutlined },
  { title: '进行中', content: 0, icon: MailOutlined },
])


const userId = ref<number | null>(null);
const grade = ref(new Date().getFullYear());
if (!user.isLogin) {
  message.error('您还没有登录，请先登录');
} else {
  userId.value = currentUser.value?.id ?? null;
}


// 统计总活动数（今年各学院第二课堂活动总数汇总）
const yearActivityConut = ref(0)
const yearSecondClassList = ref<any[]>([])
const getRaceList = async () => {
  try {
    const { data } = await getSecondClassCountYear({ year: new Date().getFullYear() })
    const list = Array.isArray((data as any)?.data)
      ? (data as any).data
      : Array.isArray(data)
        ? (data as any)
        : []
    yearSecondClassList.value = list
    yearActivityConut.value = list.reduce((sum: number, item: any) => sum + (item?.count || 0), 0)
    studentBoxList.value[0].content = yearActivityConut.value
  } catch (e) {
    console.error('获取今年总活动数失败：', e)
  }
}

const getStudentRaceList = async () => {
  // 统计学生参与活动总次数
  const studentSecondClassCount = await getStudentSecondClassCount(
    userId.value
  );
  console.log(studentSecondClassCount);

  studentBoxList.value[0].num = studentSecondClassCount.data.data;

  // 统计学生参与大创活动次数
  const studentInnovationCount = await getStudentInnovationCount(userId.value);
  studentBoxList.value[1].content = studentInnovationCount.data.data;

  // 统计学生参与第二课堂活动次数
  const pepRes = await getStudentJoinCount(userId.value);
  studentBoxList.value[2].content = pepRes.data.data;

  // 统计学生年度参与活动率
  const studentRes = await getParticipationRateByUser(
    userId.value,
    grade.value
  );
  const studentCount = ref(0);
  studentCount.value = studentRes.data.data;
  studentBoxList.value[3].content = studentCount.value;
};

// ------ ECharts ------
let pieChartInst: echarts.ECharts | null = null
let rightChartInst: echarts.ECharts | null = null
let lineChartInst: echarts.ECharts | null = null

const initCharts = async () => {
  await nextTick()
  const pieEl = document.getElementById('chart-pie')
  const rightEl = document.getElementById('chart-right')
  const lineEl = document.getElementById('chart-line')

  if (pieEl && !pieChartInst) pieChartInst = echarts.init(pieEl)
  if (rightEl && !rightChartInst) rightChartInst = echarts.init(rightEl)
  if (lineEl && !lineChartInst) lineChartInst = echarts.init(lineEl)

  window.addEventListener('resize', handleResize)
}

const handleResize = () => {
  pieChartInst?.resize()
  rightChartInst?.resize()
  lineChartInst?.resize()
}

const updateCharts = () => {
  // 使用预设的 pie 和 line 选项
  pieChartInst?.setOption(pieChart)
  lineChartInst?.setOption(lineChart)
  // 右侧柱状图用实际数据渲染
  rightChartInst?.setOption(sortRank(yearSecondClassList.value))
}

onMounted(async () => {
  await getRaceList()
  if (currentUser.value && currentUser.value.isTeacher === 0) {
    await getStudentRaceList()
  }
  await initCharts()
  updateCharts()
})

watch([yearSecondClassList, studentBoxList], () => updateCharts())

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  pieChartInst?.dispose(); pieChartInst = null
  rightChartInst?.dispose(); rightChartInst = null
  lineChartInst?.dispose(); lineChartInst = null
})

</script>


<style scoped>
/* 主题与头部 */
#homePage {
  --theme: #06b6d4;
}

.overview-header {
  margin-bottom: 16px;
}

.overview-header h2 {
  font-size: 18px;
  margin: 0;
  color: #111;
}

.overview-header p {
  margin: 6px 0 0;
  color: #666;
  font-size: 13px;
}

/* 卡片网格 */
.card-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 16px;
}

/* 单个卡片 */
.card {
  background: #fff;
  border-radius: 10px;
  border: 1px solid #eef2f7;
  box-shadow: 0 2px 8px rgba(17, 24, 39, 0.04);
  transition: all 0.2s ease-in-out;
  padding: 16px 16px 18px;
  position: relative;
  overflow: hidden;
}

.card::before {
  content: '';
  position: absolute;
  inset: 0 0 auto 0;
  height: 4px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  background-color: var(--theme);
}

.card::after {
  content: '';
  position: absolute;
  inset: 0;
  background: var(--theme);
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s ease-in-out;
}

.card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 18px rgba(17, 24, 39, 0.08);
  border-color: rgba(6, 182, 212, 0.35);
}

.card:hover::after {
  opacity: 0.10;
  /* 柔和覆盖，保持协调 */
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 12px;
  position: relative;
  z-index: 1;
}

.icon-wrap {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: rgba(6, 182, 212, 0.12);
  display: grid;
  place-items: center;
}

.icon {
  color: var(--theme);
  font-size: 18px;
}

.title {
  color: #111;
  font-weight: 600;
}

.card-body {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  margin-left: 46px;
  position: relative;
  z-index: 1;
}

.number {
  font-size: 26px;
  font-weight: 700;
  color: #111;
}

.unit {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 4px;
}

/* 空状态 */
.empty-state {
  margin-top: 12px;
  padding: 32px;
  background-color: #fff;
  border: 1px solid #eef2f7;
  border-radius: 10px;
  color: #666;
  text-align: center;
}

.chart-wrapper {
  display: flex;
  margin-top: 20px;
  height: 500px;
  gap: 20px;
}

#chart-right {
  border-radius: 8px;
  background-color: #fff;
  width: 50%;
  height: 100%;
}

#chart-pie {
  border-radius: 8px;
  background-color: #fff;
  width: 50%;
  height: 100%;
}

#chart-cloud {
  border-radius: 8px;
  background-color: #fff;
  width: 50%;
  height: 100%;
}

#chart-line {
  border-radius: 8px;
  background-color: #fff;
  width: 100%;
  height: 100%;
}
</style>
